package cheme.ProcessEditor.Parts.Streams.Tag;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.ComponentEditPolicy;
import org.eclipse.gef.requests.GroupRequest;

import cheme.ProcessEditor.Tools.CreateAfterRequest;
import cheme.ProcessModel.IChild;
import cheme.ProcessModel.IParent;
import cheme.ProcessModel.Cmds.AddCmd;
import cheme.ProcessModel.Cmds.DeleteCmd;
import cheme.ProcessModel.ProcessUnits.Streams.Tags.TagComponent;

public class PolicyTagComponentList extends ComponentEditPolicy
{
	@Override
	public Command getCommand(Request request)
	{
		if(request instanceof CreateAfterRequest)
		{
			return getAddListItemCmd((CreateAfterRequest)request);
		}
		
		return super.getCommand(request);
	}
	
	public Command getAddListItemCmd(CreateAfterRequest request)
	{
		AddCmd cmd = null;
		
		
		/* If there is a list of object to create, pick the last one
		 * (which represents the highest element in the hierarchy and also a 
		 * direct child), create a new instance of that and insert it after that.
		 */
		int listSize = request.getAfterList().size();
		if(0 != listSize)
		{
			Object child = request.getAfterList().get(listSize - 1);
			if(child instanceof EditPart)
			{
				int insertIndex = getHost().getChildren().indexOf(child);
				
				if(-1 != insertIndex)
				{
					insertIndex++; //move one past this guy
				}
				
				IParent parent = (IParent)getHost().getModel();
				cmd = new AddCmd(new TagComponent(parent), parent, insertIndex);
			}
		}

		return cmd;
	}
	
	@Override
	protected Command getDeleteCommand(GroupRequest request)
	{		
		return new DeleteCmd((IChild)getHost().getModel());
	}
}
